#include "stdafx.h"
#include "ConfigWriterSqlite.h"
#include "SQLite\DB_SQLite.h"
#include "Log\Log.h"

namespace woe
{
	ConfigWriterSqlite*	ConfigWriterSqlite::m_Instance = NULL;

	ConfigWriterSqlite::ConfigWriterSqlite()
	{
		//InitializeCriticalSection( &m_csWriteSqlite );
	}

	ConfigWriterSqlite::~ConfigWriterSqlite()
	{
		//DeleteCriticalSection( &m_csWriteSqlite );
		if ( m_Instance )
		{
			delete m_Instance;
			m_Instance = NULL;
		}
	}

	bool ConfigWriterSqlite::DoSave(const std::string& strFileName, IConfigOperator* config)
	{
		if ( !config )
		{
			LOG_DEBUG("Failed to , ConfigWriterSqlite::DoSave, the param config is NULL\n");
			return false;
		}
		CSQLiteBase* pSQLiteBase = new CSQLiteBase;
		if ( !pSQLiteBase )
		{
			LOG_DEBUG("Failed to , ConfigWriterSqlite::DoSave, new CSQLiteBase failed\n");
			return false;
		}

		//const char* s = ".db";
		//std::string newdb = strFileName;
		//newdb.append(s);
		//
		//remove( newdb.c_str() );
		//::CreateFile( newdb.c_str(), GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		//::EnterCriticalSection( &m_csWriteSqlite );
		if ( !pSQLiteBase->Open( strFileName.c_str() ) )
		{
			LOG_DEBUG_V("Failed to Open db %s ,ConfigWriterSqlite::DoSave\n",strFileName.c_str());
			return false;		
		}

		char szSQL[256] = "delete from tbl ";
		CppSQLite3DB* db = pSQLiteBase->GetDB();
		db->execDML( szSQL );

		std::string key , value;
		while( config->GetNext(key,value) )
		{
			sprintf( szSQL, "insert into tbl values('%s','%s');",key.c_str(),value.c_str() );
			db->execDML( szSQL );
		}
		//::LeaveCriticalSection( &m_csWriteSqlite );
		return true;
	}

	ConfigWriterSqlite* ConfigWriterSqlite::GetInstance()
	{
		if ( !m_Instance )
		{
			m_Instance = new ConfigWriterSqlite;
		}
		return m_Instance;
	}
}